using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Services;
using Identity.Application.Permissions.Interfaces;
using Identity.Application.RolePermissions.Commands;
using Identity.Application.UserRoles.Commands;
using Identity.Domain.Aggregates;
using MediatR;

namespace Identity.Application.RolePermissions.CommandHandlers;

public class RemovePermissionFromRoleCommandHandler : IRequestHandler<RemovePermissionFromRoleCommand, Result>
{
     private readonly IRoleService _roleService;
    private readonly IPermissionsRepository _permissionsRepository;
    private readonly IUnitOfWork _unitOfWork;

    public RemovePermissionFromRoleCommandHandler(IRoleService roleService, IPermissionsRepository permissionsRepository, IUnitOfWork unitOfWork)
    {

        _roleService = roleService;
        _permissionsRepository = permissionsRepository;
        _unitOfWork = unitOfWork;

    }

    public async Task<Result> Handle(RemovePermissionFromRoleCommand request, CancellationToken cancellationToken)
    {
        if (request.permissionIds == null) return Result.Failure("至少需要一个权限！");
        var roleData = await _roleService.GetRoleByIdAsync(request.roleId);
        if (roleData == null) return Result.Failure("角色不存在");
        var role = Role.LoadFromPersistence(roleData.Id,roleData.Code, roleData.Name,roleData.PermissionIds, roleData.Description,roleData.Status);

        foreach (var perId in request.permissionIds) role.RemovePermission(perId);
        
        var result = await _roleService.SaveRoleAsync(role);

        return Result.Success(result);
    }
}